package org.ligson.fwc.api.dto;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.ligson.fwc.api.util.JsonUtil;
import lombok.Data;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/***
 * 子类必须实现有参和无参构造
 * @TODO 想办法不需要写子类
 */
@Data
public class BasePageResponseDto<T> extends BaseResponseDto {
    @JsonIgnore
    private int totalCount;
    @JsonIgnore
    private int pageCount;
    @JsonIgnore
    private int pageSize;
    @JsonIgnore
    private int pageNum;
    @JsonIgnore
    private List<T> datas = new ArrayList<>();
    @JsonIgnore
    private Class clazz;

    public BasePageResponseDto() {
    }

    public BasePageResponseDto(int totalCount, int pageCount, int pageSize, int pageNum, List<T> datas) {
        this.totalCount = totalCount;
        this.pageCount = pageCount;
        this.pageSize = pageSize;
        this.pageNum = pageNum;
        this.datas = datas;
        setSuccess(true);
        put("totalCount", totalCount);
        put("pageCount", pageCount);
        put("pageSize", pageSize);
        put("pageNum", pageNum);
        put("datas", datas);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setData(Map<String, Object> data) {
        super.setData(data);
        setTotalCount(get("totalCount"));
        setPageCount(get("pageCount"));
        setPageSize(get("pageSize"));
        setPageNum(get("pageNum"));
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        Class<T> entityClass = (Class<T>) type.getActualTypeArguments()[0];
        System.out.println(entityClass);
        setDatas(JsonUtil.readArray(JsonUtil.toJson(data.get("datas")), entityClass));
    }
}
